<?php

class m_form_documents_Structure extends m_form_documents_StructureBase
{

	private static $instances;
	
	/**
	 * @return m_form_documents_Structure
	 */
	public static function createNew()
	{
		return new self();
	}
	
	/**
	 * @return m_form_documents_Structure
	 */
	public static function getInstanceByUniqueId($id, $lang = null)
	{
		if(is_null($lang)) $lang = f_core_Context::getInstance()->getLang();
		
		if(!isset(self::$instances[$lang][$id]))
		{
			$cache = f_core_Cache::getInstance();
			
			$key = $cache->getDocumentCacheKey($id, $lang);
			
			if($cache->hasCache($key))
			{
				return $cache->getCacheContent($key);
			}
			
			self::$instances[$lang][$id] = new self($id, $lang);
			
			$cache->putInCache($key, self::$instances[$lang][$id]);
			
			return self::$instances[$lang][$id];			
		}

		return self::$instances[$lang][$id];
	}
	
	public function getEditUrl($lang = null, $tabName = null)
    {
		if(is_null($lang))
		{
			$lang = f_core_Request::getInstance()->getParameter("docLang", $this->getLang());
		}

        if(is_null($tabName))
        {
            $tabName = 'structure';
        }

		return f_core_Routing::getUrl("editStructure", array('tabName' => $tabName, "docId" => $this->getUniqueId(), "docLang" => strtolower($lang)));
    }

	public function getDeleteUrl($lang = null)
	{
		if(is_null($lang))
		{
			$lang = f_core_Request::getInstance()->getParameter("docLang", $this->getLang());
		}

		return f_core_Routing::getUrl("deleteGeneric", array('moduleName' => 'form', "docId" => $this->getUniqueId(), "docLang" => strtolower($lang)));
	}

	public function canSlide()
	{
		return true;
	}

    public function getMenuLabel()
    {
        return $this->getLabel();
    }

    public function getIcon()
    {
        return 'field.png';
    }

    public function getListFields()
    {
        $options = array();
        
        if(!is_null($this->getListConfig()))
        {
           $options = unserialize($this->getListConfig());
        }

        $fields = f_xml_Xpath::getInstance()->fromString($this->getStructure())->getElementsFromXpath('//field');

        if(count($fields) > 0)
        {            
            foreach($fields as $k => $field)
            {
                /* @var $field f_xml_XmlElement */

                if($field->getAttributeValue('type') != 'security')
                {
                    if(count($options) > 0)
                    {
                        $isset = $this->recursiveArraySearch($options, $field->getAttributeValue('name'), 'name');

                        if($isset !== false)
                        {
                            $res = $options[$isset];

                        }
                        else
                        {
                            $res['label'] = $field->getAttributeValue('label');
                            $res['name'] = $field->getAttributeValue('name');
                            $res['type'] = $field->getAttributeValue('type');
                            $res['visible'] = false;
                        }
                    }
                    else
                    {
                        $res['label'] = $field->getAttributeValue('label');
                        $res['name'] = $field->getAttributeValue('name');
                        $res['type'] = $field->getAttributeValue('type');
                        $res['visible'] = $k < 5;
                    }

                    $result[$k] = $res;
                }
            }
            return $result;
        }

        return array();
    }

    private function recursiveArraySearch($haystack, $needle, $index = null)
{
    $aIt     = new RecursiveArrayIterator($haystack);
    $it    = new RecursiveIteratorIterator($aIt);

    while($it->valid())
    {
        if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
            return $aIt->key();
        }

        $it->next();
    }

    return false;
}

    public function getRecords($nbResult = null, $offset = null)
    {
        $docProvider = f_document_Provider::getInstance();

        $request = $docProvider ->loadDocuments('modules_form/record')
                                ->whereIsEqual('structureId', $this->getUniqueId())
                                ->addDescOrder('document_creationdate')
                                ->limit($nbResult, $offset);

        return $request->retrieveDocuments($this->getLang());
    }

    public function hasSaveAction()
    {
        $action = f_xml_Xpath::getInstance()->fromString($this->getStructure())->getElementFromXpath('onSuccess/action[@type="Save"]');
        return !is_null($action);
    }
}